<template>
  <a-modal
    v-model="visible"
    width="50vw"
    :bodyStyle="{ padding: '10px 20px'}"
    title="清洗方式维护"
    :confirmLoading="loading"    
    @ok="handleOk"
    @cancel="handleCancel"
  >      
    <div>
      <a-form-model ref="ruleForm" :model="dataForm" :rules="rules" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-model-item label="方式编号">
              <a-input v-model="dataForm.wayNoStr" disabled placeholder="自动生成"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="方式代码" prop="wayCode">
              <a-input v-model="dataForm.wayCode" allowClear placeholder="请输入"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-model-item label="方式名称" prop="wayName">
              <a-input v-model="dataForm.wayName" allowClear placeholder="请输入"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="方式描述" prop="wayDesc">
              <a-input v-model="dataForm.wayDesc" allowClear placeholder="请输入"/>
            </a-form-model-item>
          </a-col>
        </a-row>        
      </a-form-model>
      <div v-show="false">
        <section>                
          <div class="section-header">
            <div class="title">适用系统与清洗时长关系表</div>            
            <div class="btn-line">
              <a-button class="hte-btn add-btn" type="primary" @click="handAction('add')">插入</a-button>                       
              <a-button class="hte-btn" @click="handAction('del')">删除</a-button>
            </div>
          </div>
          <a-table
            class="hte-table-content"
            :columns="fileColumns"
            :scroll="{ x: true }"
            :data-source="fileData"
            :pagination="false"
            :loading="tabLoading"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"            
            rowKey="rowKey"
            bordered
            size="middle"
          >
            <template slot="system" slot-scope="text, record, index">
              <a-select
                show-search
                placeholder="请选择"
                v-model="record.system"
                @change="(e) => handleChange(e, record, index)"
                >
                <a-select-option v-for="i in 11" :key="i">
                  系统{{ i }}
                </a-select-option>
              </a-select>
            </template>
            <template slot="duration" slot-scope="text, record">
              <a-input v-model="record.duration"></a-input>
            </template>
          </a-table>
        </section>
      </div>
    </div>
  </a-modal> 
</template>
<script>
import {getAction, postAction,getActionAsync } from '@/api/manage'

export default {
  name: 'BurdenAddModal',
  props: {
    washType:{
      type:String
    },
  },
  data() {
    return {
      visible: false,
      dataForm: {},
      rules: {
        wayCode: [{ required: true, message: '请输入', trigger: 'blur' }],
        wayName: [{ required: true, message: '请输入', trigger: 'blur' }],
        cancelMemo: [{ required: true, message: '请输入', trigger: 'blur' }],
      },
      loading: false,
      modalType: '', // add新增  upd修改
      url: {
        save: '/hteWashWay/save',
        queryById: '/hteWashWay/info/' 
      },
      // 系统表
      fileColumns: [
        {
          title: '序号',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          },
          isImportExcelColumns:false
        },        
        { title: '系统',dataIndex: 'system',width: 120,align: 'center',scopedSlots: { customRender: 'system' }},
        { title: '清洗时长(h)', dataIndex: 'time', width: 120, align: 'center',scopedSlots: { customRender: 'duration' }},        
      ],
      fileData: [], 
      selectedRowKeys: [],
      selectionRows: [],
      tabLoading: false,
      dictList: [],
    }
  },
  mounted() {
  },
  methods: {
    showVisible(id) {      
      if(id){        
        this.modalType = 'upd'
        this.$set(this.dataForm, 'orderNo', id)
        this.initData(id) // 修改        
      }
      this.modalType = 'add'
      this.visible = true            
    },
    handleCancel() {
      this.visible = false
      this.dataForm = {}
      this.fileData = []
      this.selectedRowKeys = []
      this.selectionRows = []
      this.$refs.ruleForm.resetFields()
    },
    handleOk(){
      this.loading = true
      this.$refs.ruleForm.validate(valid => {
        if (valid) {  
          // if(!this.fileData.length){
          //   this.$message.warning('请先选择适用系统！')
          //   return
          // }
          // const flag2 = this.fileData.some(item=>{
          //   return !item.system
          // })      
          // if(flag2){
          //   this.$message.warning('请先完成系统配置！')
          //   return
          // }
          // const array = this.fileData.map(item=>{
          //   return item.system
          // })
          // if(new Set(array).size !== this.fileData.length){
          //   this.$message.warning('适用系统不能重复！')
          //   return
          // }
          debugger
          // const url = this.modalType == 'add' ? this.urls.addBurden : this.urls.updateBurden
          this.dataForm.systemList = this.fileData;
          this.dataForm.washType = this.washType
          postAction(this.url.save, this.dataForm).then(res => {
            if (res.success) {
              this.$emit('ok')
              this.handleCancel()
              this.$message.success(`${this.modalType == 'add' ? '新增成功' : '修改成功'}`)
            } else {
              this.$message.error('操作失败:' + res.message)
            }
          })                                      
        }        
      })
      this.loading = false
    },
    initData(id){
      this.loading = true
      getAction(this.url.queryById +id).then(res => {
        if (res.success) {
          this.dataForm = res.result
          this.fileData = res.result.systemList
        } else {
          this.$message.error('查询失败:' + res.message)
        }
        this.loading = false
      })
    },
    /**
     * 适用系统与清洗时长关系表
     */
    async handleChange(e, record, index){             
      // //todo 根据系统编号查询对应的时长    
      // let res = await this.searchAwait(e)
      // if(!res) return
      // this.$set(this.fileData[index], 'time', res.applyDeptId)
    },
    async searchAwait(id){
      let result = null     
      await getActionAsync(this.url.queryOrderById, {id: 134 || id}).then((res) => {
        if (res.code == 200) {
          // todo 根据系统编号查询对应的时长        
          result = res.result 
        } else {
          this.$message.warning('操作数据出错:' + res.message)
        }
      })
      return result 
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    handAction(type) {
      switch (type) {
        case 'add':
          // 新增
          this.selectedRowKeys = []
          this.selectionRows = []
          this.fileData.push({rowKey: this.fileData.length})
          break
        case 'del':
          // 删除，可多选
          const that = this
          if (this.selectedRowKeys.length == 0) {
            this.$message.warning('请选择至少一条数据！')
            return
          }
          this.$confirm({
            title: '确认删除',
            content: '请确认是否删除此系统?',
            onOk: function () {
              that.selectionRows.forEach(key => {              
                const index = that.fileData.findIndex(v => v.rowKey === key.rowKey);
                if(index != -1){
                  that.fileData.splice(index, 1);  
                }              
              });
            },
          })
          break
        default:
          break
      }
    }
  },
}
</script>
<style lang="less" scoped>
.section-header {
  font-size: 16px;
  font-weight: bold;
  position: relative;
  padding-left: 14px;
  color: #333333;
  margin-bottom: 14px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  .title{position: relative;
    &:before {
      content: '';
      position: absolute;
      top: 10%;
      width: 4px;
      left: -13px;
      background-color: #47a4fa;
      border-radius: 1px;
      height: 80%;
    }
  }  
  .btn-line {flex: 1;display: flex;justify-content: flex-end;
    button{margin-right: 10px;
      &:last-of-type{margin-right: 0;}
    }
  }
}
</style>
